/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package demo.model.util;

import java.io.File;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLClassLoader;
import java.util.HashMap;
import java.util.Locale;
import java.util.Map;
import java.util.ResourceBundle;

/**
 *
 * @author Admin
 */
public class LanguageBundle {

    String name;
    Boolean isBuilt;
    ResourceBundle resource;
    static Map<String, LanguageBundle> languages;

    private LanguageBundle(String name) {
        this.name = name;
        this.isBuilt = false;
    }

    public void buildPath(String locationPath) throws MalformedURLException {

        if (!this.isBuilt && !locationPath.equals("")) {
            File file = new File(locationPath);

            if (file != null) {

                URL[] urls = {file.toURI().toURL()};
                ClassLoader loader = new URLClassLoader(urls);
                this.resource = ResourceBundle.getBundle(name, Locale.getDefault(), loader);
                this.isBuilt = true;

            }
        }

    }

    public static LanguageBundle getInstance(String name) {
        if (LanguageBundle.languages == null) {
            languages = new HashMap<String, LanguageBundle>();
        }
        if (LanguageBundle.languages != null) {
            if (!LanguageBundle.languages.containsKey(name)
                    || LanguageBundle.languages.get(name) == null) {
                LanguageBundle lang = new LanguageBundle(name);
                LanguageBundle.languages.put(name, lang);
            }
            return LanguageBundle.languages.get(name);
        }
        return null;
    }

    public Boolean isBuilt() {
        return this.isBuilt;
    }

    public void resetBuild(String locationPath) throws MalformedURLException {
        this.isBuilt = false;
        this.buildPath(locationPath);
    }

    public String get(String key) {
        if (this.resource != null && this.resource.containsKey(key) && this.resource.getString(key) != null) {
            return this.resource.getString(key);
        }
        return key;
    }

    public static String getLang(String key, String lang) throws Exception {
        LanguageBundle langueBundle = LanguageBundle.getInstance(lang);
        if (langueBundle.isBuilt) {
            return langueBundle.get(key);
        }
        throw new Exception(PropertiesBundle.MSG_EXCEPTION.getString("build_language"));
    }
}
